﻿using AutoMapper;
using bookmeetingroom.Data;
using bookmeetingroom.Data.Entities;
using bookmeetingroom.Helper;
using bookmeetingroom.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace bookmeetingroom.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Produces("application/json")]
    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "Admin")]
    public class BuildingController : ControllerBase
    {
        private readonly ApplicationDbContext _dbContext;
        private readonly ILogger<BuildingController> _logger;
        private readonly IMapper _mapper;

        public BuildingController(ApplicationDbContext dbContext, ILogger<BuildingController> logger, IMapper mapper)
        {
            _dbContext = dbContext;
            _logger = logger;
            _mapper = mapper;

        }

        [HttpGet]
        public ActionResult List()
        {
            Guid guid = this.User.GetCompanyID();

            var buildings = _dbContext.Buildings.Where(n => n.CompanyId == guid).OrderByDescending(n => n.UpdatedTime).ToArray();

            return Ok(new { message = "", data = buildings });

        }

        [HttpPost]
        public async Task<ActionResult> Save(BuildingModel buildingModel)
        {
            var c = this.User.GetCompanyID();
            Console.WriteLine(c);

            if (!ModelState.IsValid)
                return BadRequest(ModelState.GetErrorMessages());

            if (buildingModel.Id <= 0)
            {


                Building building = new Building
                {
                    Name = buildingModel.Name,
                    Address = buildingModel.Address,
                    Default = false,
                    CompanyId = this.User.GetCompanyID(),
                };

                building.MarkAdded();

                _dbContext.Add(building);
            }
            else
            {
                var building = _dbContext.Buildings.Find(buildingModel.Id);

                if (building == null)
                {
                    return BadRequest("不能找到此场所");
                }

                building = _mapper.Map(buildingModel, building);

                _dbContext.Update(building);
            }
            await _dbContext.SaveChangesAsync();

            var guid = this.User.GetCompanyID();

            var buildings = await _dbContext.Buildings.Where(n => n.CompanyId == guid).OrderByDescending(n => n.UpdatedTime).ToArrayAsync();

            return Ok(new { message = (buildingModel.Id <= 0) ? "建立成功" : "修改成功", data = buildings });

        }
        [HttpGet("{id}")]
        public async Task<ActionResult> Detail(int id)
        {
            Guid guid = this.User.GetCompanyID();

            var building = await _dbContext.Buildings.Where(n => n.CompanyId == guid && n.Id == id)
                .SingleOrDefaultAsync();

            return Ok(new { message = "", data = building });
        }
        [HttpPost("Remove/{id}")]
        public async Task<ActionResult> Remove(int? id)
        {
            if (!id.HasValue) return BadRequest("不能找到此场所");

            var building = await _dbContext.Buildings.FindAsync(id.Value);

            if (building.Default)
            {
                return BadRequest("默认的场所不能删除");
            }

            if (building != null)
            {
                _dbContext.Buildings.Remove(building);

                await _dbContext.SaveChangesAsync();
            }

            var guid = this.User.GetCompanyID();

            var buildings = await _dbContext.Buildings.Where(n => n.CompanyId == guid).OrderByDescending(n => n.UpdatedTime).ToArrayAsync();

            return Ok(new { message = "删除成功", data = buildings });


        }

    }
}
